# -*- coding: utf-8 -*-
import concurrent.futures
import re
import time
import datetime
import random
import json

import requests
from bs4 import BeautifulSoup

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core import serializers
from django.utils import timezone

from common.tasks import wuliu_api
from common.models import ViewModel
from common import sample, wuliu


class Command(BaseCommand):
    """
    add waybill to wuliu
    """
    help = 'add waybill to wuliu'

    def add_arguments(self, parser):
        parser.add_argument('--repeat', type=int, default=1, help='循环次数')

    def handle(self, *args, **options):
        self.base_url = ('http://192.168.1.24:10001/api/%s')
        self.repeat_count = int(options['repeat'])
        self.org_user = wuliu.get_org_user(self.base_url)
        self.bill_new()

    def _get_bill(self, start_org_id, end_org_id, start_user_id):
        m = ViewModel()
        #m.startDepartment = start_org_id
        m.endDepartId = end_org_id
        m.userId = start_user_id
        m.departId = start_org_id
        m.goodsList = [
            dict(goodsName=sample.goods_name(),
                 pack=sample.pack(),
                 cubage=random.randint(1, 20),
                 weight=random.randint(1, 100),
                 numbers=random.randint(1, 999),
                 premiumAmount=random.randint(4000, 10000))
        ]
        m.shipper = sample.name()
        m.consignee = sample.name()
        m.shipperPhone = sample.phone()
        m.consigneePhone = sample.phone()
        m.balanceMethod = sample.balance_method()
        m.takeMethod = sample.take_method()
        m.isNeedDeliveryProof = random.randint(0, 2) % 2
        # m.goodsName = sample.goods_name()
        # m.pack = sample.pack()
        # m.cubage =random.randint(1,20)
        # m.weight = random.randint(1,100)
        # m.numbers = random.randint(1,999)
        # m.premiumAmount = random.randint(4000,10000)
        m.transportCost = random.randint(1, 1000)
        m.deliveryCost = random.randint(1, 500)
        # math.ceil(random.random()*1000)
        m.goodsCost = random.randint(1, 10000)
        # m.premiumCost = round(m.premium_amount * 0.00025,3)
        return m

    def bill_new(self):
        url = self.base_url % ('billnew/create')

        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            future_to_url = {}
            for page in range(0, self.repeat_count):
                for start_org_id, start_user_id in self.org_user.items():
                    for end_org_id, _ in self.org_user.items():
                        if start_org_id == end_org_id:
                            continue
                        bill_model = self._get_bill(
                            start_org_id, end_org_id, start_user_id)

                        key = '%s-%s-%s' % (start_org_id, end_org_id, page)
                        future_to_url[executor.submit(
                            wuliu_api.delay, url, 'POST', bill_model.__dict__)] = key
                        # break
                # break
            for future in concurrent.futures.as_completed(future_to_url):
                key = future_to_url[future]
                try:
                    data = future.result()
                except Exception as exc:
                    self.stdout.write(self.style.ERROR(
                        '%s generated an exception: %s' % (key, exc)))
                    print(exc)
                else:
                    self.stdout.write(self.style.SUCCESS(
                        '%s page is ok %s' % (key, data, )))
